<?php

namespace Home\Controller;


/**
 * 商户控制器
 *
 */
class ShopController extends HomeController
{

    /**
     * 商户入驻
     */

    public function add()
    {
        $uid = I('get.uid');

        if (IS_POST) {
            $model = D('Kbxx');
            $isAddKbxx = $model->where('uid=' . $uid)->count();

            if (!$isAddKbxx) {
                //未添加商户信息
                $this->showError('请联系管理员开通权限');

            }

            $params = I('post.');
            $params['uid'] = $uid;

            if (empty($_POST['name'])) {
                $this->showError('请填写姓名');
            }

            if ($params['rate2'] > $params['rate']) {
                $this->showError('费率不可高于平台费率');
            }

            if ($params['rate2'] < 0.6) {
                $this->showError('费率不可低于0.6');
            }

            $res = M('kbsh')->add($params);

            if ($res !== false) {
                //测试成功才往redis加

//                $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
//
//                $rediskey = \Home\Logic\PayLogic::getRedisKeyByType(2);
//                $redis->lpush($rediskey,$res);
                $this->showSuccess();
            } else {
                $this->showError('入驻失败');
            }
        }

    }

    /**
     * 商户授权码url地址
     */
    public function getQrcodeUrl()
    {
        $uid = I('uid');
        $kbsh_id = I('kbsh_id'); //码商id

        $kbsh = M('kbsh')->find($kbsh_id);

        $one = D('Kbxx')->where('uid=' . $uid)->find();
        if (empty($one)) {
            $this->showError('没有这个商户 ');
        } else {

            if (empty($one['name'])) {
                //有这个商户  但是没有上传身份证信息
                $this->showError('商户信息不完整');
            } else if (!empty($one['name']) && $one['real_status'] == 0) {
                // 有这个商户 已上传身份证 但未通过验证
                $this->showError('您的认证信息已上传，请耐心等候人工审核~');
            }
        }

//        $adata=D('Adata')->where(['id'=>1])->find();
        $adata = M('shouquan')->find();
        $appid = $adata['appid'];

        //&kbsh_id=$kbsh_id
//        $url = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=$appid&redirect_uri=http://hbxyk.hihaoge.me/pay.php&uid=$uid&kbsh_id=$kbsh_id";
        $url = "http://hbxyk.hihaoge.me/home/index/authorization?uid=$uid&kbsh_id=$kbsh_id";
        $url = urlencode($url);
        //输出二维码
//        QRcode($url,8);

        $this->showSuccess('', ['url' => $url, 'alipay' => $kbsh['alipay']]);
    }

    /**
     * 码商商户列表
     */
    public function index()
    {
        //status 授权状态  use_status 使用状态
        $name = I('get.name', ''); //商户名称
        $use_status = I('get.use_status', 9); //使用状态

        $condition = array();
        $condition['uid'] = array('eq', $this->uid);
        if ($name) {
            $condition['name'] = array("like", "%$name%");
        }

        if ($use_status != 9) {
            //不是全部
            $condition['use_status'] = array('eq', $use_status);
        }

        $one = D('Kbxx')->where(['uid' => $this->uid])->find();
//        $info = D('Kbsh')->where(['uid' => $this->uid])->order('create_time desc')->select();

        $totalCount = D('kbsh')->where($condition)->count();
        $list = $this->lists('Kbsh', $condition);

        if (!$list) {
            $kbsh = array();
        } else {
            $kbsh = $list;
        }

        $time1 = strtotime(date("Ymd"));
        $time2 = strtotime(date("Ymd")) + 86400;

        if (!empty($kbsh)) {
            foreach ($kbsh as $k => $v) {
                //今日交易额
                $dingdan = D('Dingdan')->where("status=1 and `seller_id`='$v[user_id]' and `pay_time` between '$time1' and '$time2'")->select();
                $todaymoney = 0.00;
                $todayDivide = 0.00;
                foreach ($dingdan as $ko => $vo) {
                    $todaymoney = $todaymoney + $vo['pay_money'];
//                    $todayDivide += $vo['yh_money'];
                }
                $kbsh[$k]['totayMoney'] = $todaymoney;
//                $kbsh[$k]['todayDivide'] = $todayDivide;


                //今日分佣
//                $todayDivide = D('Split')->where(['uid' => $this->uid, 'status' => 1,'seller_id' => $v['user_id']])->where("`time` between '$time1' and '$time2'")->sum('sh_money'); //口碑收益获得
                $todayfenyong = D('Split')->where([ 'status' => 1,'seller_id' => $v['user_id']])->where("`time` between '$time1' and '$time2'")->sum('sh_money'); //口碑收益获得
//                $todayDivide = $money_in*($v['rate'] - $v['rate2']);
//                $todayDivide = price_format($todayDivide);
//                $this->showSuccess('',D('Split')->getLastSql());
                is_null($todayfenyong) ? $kbsh[$k]['todayDivide'] = 0.00 : $kbsh[$k]['todayDivide'] = $todayfenyong;

            }
        }

        $this->showSuccess('', [
            'totalCount' => $totalCount,

            'kbxx' => $one, //码主信息
            'kbsh' => $kbsh //码商信息
        ]);

    }

    public function detail()
    {
        $id = I('get.id');
        $info = M('kbsh')->where('id=' . $id)->find();
        $this->showSuccess('', $info);
    }

    /**
     * 修改密玥
     */
    public function secret(){
        $id = I('get.id');
        if(IS_POST){
            $appid = I('post.appid');
            $secret = I('post.secret');
            $public = I('post.public');
            $user_id = I('post.user_id');//支付宝伙伴id

            $res = M('kbsh')->where(['id' => $id])->save([
                'appid' => $appid,
                'secret' => $secret,
                'public' => $public,
                'user_id' => $user_id //支付宝伙伴id
            ]);

            if($res !== false){
                $this->showSuccess();
            }else{
                $this->showError('操作失败');
            }
        }
    }

    public function other(){
        $data = [
            //状态:0=未测试,1=正常,2=异常
            'status' => [
                ['id' => 0, 'value' => '未测试'],
                ['id' => 1, 'value' => '正常'],
                ['id' => 2, 'value' => '异常']
            ],

            //使用状态:0=离线,1=在线,2=未授权,3=已授权
            'use_status' => [
                ['id' => 0, 'value' => '离线'],
                ['id' => 1, 'value' => '在线']
            ]
        ];

        $this->showSuccess('',$data);
    }

    /**
     * 修改商户状态
     * @param int $id 商户id
     * @param int $value 值
     */
    public function updateStatus(){
//        $id,$value,$type
        $id = I('post.id');
        $value = I('post.value');
        $type = I('post.type');

        $kbsh = M('kbsh')->find($id);
        if($kbsh['handle_status'] != 1){
            $this->error('店铺审核通过后才能上线！');
        }

        if($kbsh['status'] != 1){
            $this->error('店铺未测试或是异常！');
        }


        $param = ['use_status' => $value];

        $res = M('kbsh')->where(['id' => $id])->save($param);
        if($res !== false){

            if($value == 1){
                \Home\Logic\ShopLogic::addRedisShop(2,$id);
            }else{
                \Home\Logic\ShopLogic::delRedisShop(2,$id);

            }
            $this->showSuccess('修改成功');
        }else{
            $this->showError('修改失败');
        }
    }

    /**
     * 商户经营数据
     * @param int $id 商户id
     */
    public function jingying($id){
        $kbsh = M('kbsh')->where(['id' => $id])->find();

        $alipayPid = $kbsh['user_id'];
        $today = date('Ymd');
        $yestoday = date('Ymd',strtotime('-1 day'));
        $dingdanList = M('dingdan')->alias('d')
            ->join('__SPLIT__ s on d.id=s.dingdan_id')
            ->where(['d.seller_id' => $alipayPid])
            ->field('danhao,buyer,pay_money,sh_money,pay_time')
            ->select();

//        echo M('dingdan')->getLastSql();exit;

        //今日收款
        ;
        $todayDingdan = M('dingdan')->query("SELECT sum(pay_money) as money FROM jd_dingdan WHERE seller_id=".$alipayPid." and  FROM_UNIXTIME(createtime, '%Y%m%d')=$today");

        $yestodayDingdan = M('dingdan')->query("SELECT sum(pay_money) as money FROM jd_dingdan WHERE seller_id=".$alipayPid." and  FROM_UNIXTIME(pay_time, '%Y%m%d')=$yestoday");
        $todayTiCheng = M('split')->query("SELECT sum(sh_money) as money FROM jd_split WHERE seller_id=".$alipayPid." and  FROM_UNIXTIME(time, '%Y%m%d')=$today");

        $todayTotal = M('dingdan')->query("SELECT count(*) as count FROM jd_dingdan WHERE seller_id=".$alipayPid." and  FROM_UNIXTIME(pay_time, '%Y%m%d')=$today");
        $todaySuccess = M('dingdan')->query("SELECT count(*) as count FROM jd_dingdan WHERE seller_id=".$alipayPid."  and status=1 and FROM_UNIXTIME(pay_time, '%Y%m%d')=$today");

        $success = $todaySuccess ? $todaySuccess[0]['count'] : 0;
        $total = $todayTotal ? $todayTotal[0]['count'] : 0;

        if($total == 0){
            $rate = 0;
        }else{
            if($success){
                $rate = round($todaySuccess/$todayTotal*100);
            }else{
                $rate = 0;
            }
        }

        $data = [
            'jinRiShouKuan' => $todayDingdan ? $todayDingdan[0]['money'] : 0,
            'jinRiTiCheng' => $todayTiCheng[0]['money'] ? $todayTiCheng[0]['money'] : 0,
            'ZuoRiShouKuan' => $yestodayDingdan[0]['money'] ? $yestodayDingdan[0]['money'] : 0,
            'jinRiChengGong' => $success,
            'jinRiDingDan' => $total,
            'jinRiChengGongLv' => $rate,
            'dingDanList' => $dingdanList ? $dingdanList : []
        ];

        $this->showSuccess('',$data);
    }

    /**
     * 删除
     */
    public function del(){
        $id = I('get.id');
        $res = M('kbsh')->delete($id);
        if($res > 0){
            $redis = new \Predis\Client(C('REDIS'),['prefix' => C('REDIS_PREFIX')]);
            $rediskey = \Home\Logic\PayLogic::getRedisKeyByType(2);
            $redis->lrem($rediskey,1,$id);
            $this->showSuccess('删除成功');
        }else{
            $this->showError('删除失败');
        }
    }

    /**
     * 测试店铺防卡单 (花呗)
     * @param int $id 店铺id
     */
//    public function testshop($id){
//        Vendor('dangmianfu_demo_php.f2fpay.qrpay_test');
//        $alipay = new \Alipay;
//        $res = \Home\Logic\PayLogic::huabeitest($id,$danhao,$alipay);
//        if($res['code'] == 1){
//            $this->showSuccess($res['msg']);
//        }else{
//            $this->showError($res['msg'],$res['data']);
//        }
//    }












}